/**
 * 代码生成器数据请求
 *
 * @版权所有 rem.studio
 */
import { queryGenerator, queryFieldByGeneratorId, deleteGenerator, addGenerator, updateGenerator, exportGenerator, generateResource } from '@/services/devApi';

export default {
  namespace: 'generator',

  state: {
    data: {
      list: [],
      pagination: {}
    },
    fieldData: {
      list: [],
      count: 0
    }
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(queryGenerator, payload);
      yield put({
        type: 'save',
        payload: response
      });
    },
    *fetchFieldData({ payload }, { call, put }) {
      const response = yield call(queryFieldByGeneratorId, payload);
      yield put({
        type: 'saveFieldData',
        payload: response
      });
      return response;
    },
    *add({ payload }, { call, put }) {
      const response = yield call(addGenerator, payload);
      yield put({
        type: 'save',
        payload: response
      });
      if (!response.message) return;
      return response;
    },
    *delete({ payload }, { call, put }) {
      const response = yield call(deleteGenerator, payload);
      yield put({
        type: 'save',
        payload: response
      });
      if (!response.message) return;
      return response;
    },
    *update({ payload }, { call, put }) {
      const response = yield call(updateGenerator, payload);
      yield put({
        type: 'save',
        payload: response
      });
      if (!response.message) return;
      return response;
    },
    *export({ payload }, { call, put }) {
      const response = yield call(exportGenerator, payload);
      yield put({
        type: 'save',
        payload: response
      });
      return response;
    },
    *generate({ payload }, { call, put }) {
      const response = yield call(generateResource, payload);
      yield put({
        type: 'save',
        payload: response
      });
      return response;
    }
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload.data
      };
    },
    saveFieldData(state, action) {
      return {
        ...state,
        fieldData: action.payload.data
      };
    }
  }
};
